'''# built_in'''
import os
import importlib
import traceback
import configparser
from datetime import datetime

'''# custom'''
from common import GSDSTORE, MODULEDATA, PROJECTROOT
from dataRead import excel_Read
from Interface.interface_Auxiliary_Class import GetInformationClass
from Interface.common_Interface_Class import CommonInterfaceClass
from utils.log.trusteeship import trusteeship


class collector(object):
    @classmethod 
    def run(cls):
        '''Initialize the clear capture'''
        if os.path.exists(f"{GSDSTORE['WORKPATH']['ROOT']}\\__st__.py"):
            spec = importlib.util.spec_from_file_location('ST', f"{GSDSTORE['WORKPATH']['ROOT']}\\__st__.py")
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            
            cls.suite_setup = getattr(module, 'suite_setup')
            cls.suite_teardown = getattr(module, 'suite_teardown')
        
        '''Capture plug-in'''
        cfp = configparser.ConfigParser()
        pluginList = os.listdir(f"{PROJECTROOT}\\plugins")
        for plugin in pluginList:
            moduleini = [py for py in os.listdir(f"{PROJECTROOT}\\plugins\\{plugin}") if os.path.splitext(f"{PROJECTROOT}\\plugins\\{plugin}\\{py}")[1] == ".ini" ][0]
            
            cfp.read(f"{PROJECTROOT}\\plugins\\{plugin}\\{''.join(moduleini)}", encoding='utf-8')
            name = cfp.get('Information', 'NAME')
            detail = cfp.get('Information', 'DETAILE')
            state = cfp.get('Information', 'STATE')
            module_Class = getattr(importlib.import_module(f"plugins.{plugin}.{name}"), f'{name}')  # 动态导入

            MODULEDATA[name] = {'information':{}, 'object': object}
            MODULEDATA[name]['information']['name'] = name
            MODULEDATA[name]['information']['detail'] = detail
            MODULEDATA[name]['information']['state'] = state
            MODULEDATA[name]['object'] = module_Class()


class cases(object):

    def __repr__(self) -> str:
        return "测试用例执行控制脚本/逻辑用例脚本"

    def __init__(self) -> None:
        '''全局数据'''
        self.__interfacePath = GSDSTORE['WORKPATH']['interfacePath']
        self.__casesPath = GSDSTORE['WORKPATH']['casesPath']
        self.__elementPath = GSDSTORE['WORKPATH']['elementPath']
        self.__resultPaht = GSDSTORE['WORKPATH']['resultPaht']
        self.__resultFileName = f"测试报告{datetime.now().strftime('%Y-%m-%d %H_%M_%S')}"
        self.__resultSummary = []

        '''object对象'''
        self.__auxiliaryInterface_Object = GetInformationClass()
        self.__commonInterface_Object = CommonInterfaceClass()

    def __call__(self) -> None:
        '''初始化'''
        trusteeship.test_start()
        try:collector.suite_setup()
        except Exception as error:trusteeship.exceptinfo("Initial blocking:"); raise Exception
        
        '''用例'''
        for filePath in GSDSTORE['START']['testCaseFile']:
            '''目录结构追踪'''
            thisFolderPaht = filePath.split('\\')[:-1]
            subFolderPath = "\\".join(thisFolderPaht[thisFolderPaht.index(self.__casesPath) + 1:])
            interFolderPath = f"{GSDSTORE['START']['packetPath']}\\{self.__interfacePath}\\{subFolderPath}" if subFolderPath else f"{GSDSTORE['START']['packetPath']}\\{self.__interfacePath}"
            elementFolderPath = f"{GSDSTORE['START']['packetPath']}\\{self.__elementPath}\\{subFolderPath}" if subFolderPath else f"{GSDSTORE['START']['packetPath']}\\{self.__elementPath}"
            
            try:
                '''interface'''
                if GSDSTORE['START']['interfaceSwitch']:
                    if not self.__auxiliaryInterface_Object(): raise Exception
                    if not self.__commonInterface_Object(f"{interFolderPath}\\InterfaceData.yaml"): raise Exception
            except Exception as error:
                print(traceback.format_exc()); break
            else:
                try:
                    '''process'''
                    testCase_Object = excel_Read.TestCase()  # 实例化“用例步骤读取、操作”类对象
                    variable = testCase_Object.testCase(filePath, f"{elementFolderPath}\\elementData.yaml", f"{self.__resultPaht}\\{self.__resultFileName}")
                    self.__resultSummary.append(variable)
                except Exception as error:
                    print(traceback.format_exc()); break
        '''清除'''
        try:collector.suite_teardown()
        except Exception as error:trusteeship.exceptinfo("Clear blockage:")
        trusteeship.test_end(self.__resultSummary)